//
//  JSQAudioVoice.m
//  Conversation
//
//  Created by C_HAO on 15/9/29.
//  Copyright © 2015年 CHAOO. All rights reserved.
//

#import "JSQAudioVoice.h"
#import "JSQMessageTools.h"

@interface JSQAudioVoice ()

@property(nonatomic, strong) NSTimer *timer;

@end

@implementation JSQAudioVoice

- (instancetype)initWithFilePath:(NSString *)filePath {
    self = [super init];
    if (self) {

        AVAudioSession *session = [AVAudioSession sharedInstance];
        NSError *sessionError;
        [session setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];
        if (sessionError) {
            NSLog(@"Error setting category: %@", [sessionError description]);
        }
        [session setActive:YES error:&sessionError];
        if (sessionError) {
            NSLog(@"Error setting Active: %@", [sessionError description]);
        }


        NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc] init];
        [recordSetting setValue:[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey];
        [recordSetting setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];
        [recordSetting setValue:[NSNumber numberWithInt:2] forKey:AVNumberOfChannelsKey];
        [recordSetting setValue:[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
        [recordSetting setValue:[NSNumber numberWithInt:AVAudioQualityHigh] forKey:AVEncoderAudioQualityKey];

        _fileName = [[filePath componentsSeparatedByString:@"/"] lastObject];
        _filePath = filePath;
        NSURL *URL = [NSURL fileURLWithPath:_filePath];
        NSError *error;
        _audioRecorder = [[AVAudioRecorder alloc] initWithURL:URL settings:recordSetting error:&error];
        if (!_audioRecorder.prepareToRecord) {
            NSLog(@"AVAudioRecorder Not Ready");
        }

        _audioRecorder.meteringEnabled = YES;


    }
    return self;
}

- (void)start {
    [_audioRecorder record];
    _timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(changeImage) userInfo:nil repeats:YES];
}

- (void)over {
    [_audioRecorder stop];
    [_timer invalidate];
    _timer = nil;
}

- (void)cancel {
    [_timer invalidate];
    _timer = nil;
    [_audioRecorder stop];
    [_audioRecorder deleteRecording];
}

- (void)changeImage {
    [_audioRecorder updateMeters];
    float avg = [_audioRecorder averagePowerForChannel:0];
    float minValue = -60;
    float range = 60;
    float outRange = 60;
    if (avg < minValue) {
        avg = minValue;
    }
    float decibels = (avg + range) / range * outRange;
    if (_voice) {
        _voice(decibels, _audioRecorder.currentTime);
    }
}

@end
